package com.orion.smart.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author <a href="http://github.com/athc">dujf</a>
 * @date 2018/9/10
 * @since JDK1.8
 */
@RestController
@RequestMapping("/redis/string")
public class RedisStringController {

  private final RedisTemplate redisTemplate;

  @Autowired
  public RedisStringController(RedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
  }

  /**
   *
   */
  @PostMapping
  public void setString() {
    //设置过期时间
    redisTemplate.opsForValue().set("name", "name", 10, TimeUnit.MINUTES);
    //从第几个字符开始替换
    redisTemplate.opsForValue().set("name", "nana", 2);
    //多个键值对存取
    Map map = new HashMap<>();
    map.put("realName", "zhang");
    map.put("amount", 100);
    redisTemplate.opsForValue().multiSet(map);
  }

  /**
   */
  @GetMapping
  public void getString() {
    Object result = null;

    //读取单个值
    result = redisTemplate.opsForValue().get("realName");
    logger.info(String.valueOf(result));

    //读取多个值
    List<String> list = new ArrayList<>();
    list.add("name");
    list.add("amount");
    //传入hashkey集合取出value
    result = redisTemplate.opsForValue().multiGet(list);
    logger.info(String.valueOf(result));

    //set value and return old value
    result = redisTemplate.opsForValue().getAndSet("name", "wangwu");
    logger.info(String.valueOf(result));

    //获取一段字符
    result = redisTemplate.opsForValue().get("realName", 1, 3);
    logger.info(String.valueOf(result));
  }


  private Logger logger = LoggerFactory.getLogger(RedisStringController.class);
}
